/**
 * SerializeUtils
 * 
 * 31/12/2013
 * 
 * Copyright GPL
 */
package com.jtmproject.classes;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;

/**
 * This class serializes and deserializes objects
 * 
 * @author Javier Tejedor
 */
public class SerializeUtils {

	/**
	 * this deserializes a buffer
	 * @param readBuf
	 * @return
	 */
	public static Object deserialize(byte[] readBuf){
		
		ByteArrayInputStream b = new ByteArrayInputStream(readBuf);

		try {

			ObjectInputStream o = new ObjectInputStream(b);
			return o.readObject();

		} catch (StreamCorruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	/**
	 * this serializes a object
	 * @param object
	 * @return
	 */
	public static byte[] serialize(Object object){
		
		ByteArrayOutputStream b = new ByteArrayOutputStream();

		try {
			
			ObjectOutputStream o = new ObjectOutputStream(b);
			o.writeObject(object);
			return b.toByteArray();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
}
